<template>
  <div v-if="pageStatus === 1">
    <ContentWrap>
      <!-- 搜索工作栏 -->
      <el-form ref="queryFormRef" :inline="true" :model="paramsData" class="-mb-15px" label-width="auto">
        <el-form-item label="申请编号" prop="code">
          <el-input v-model="paramsData.code" class="!w-360px" clearable placeholder="请输入申请编号" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="paramsData.projectName" class="!w-360px" clearable placeholder="请输入项目名称" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="项目编号" prop="projectCode">
          <el-input v-model="paramsData.projectCode" class="!w-360px" clearable placeholder="请输入项目编号"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="主合同名称" prop="mainContract">
          <el-input v-model="paramsData.mainContract" class="!w-360px" clearable placeholder="请输入主合同名称"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="主合同编号" prop="mainContractCode">
          <el-input v-model="paramsData.mainContractCode" class="!w-360px" clearable placeholder="请输主合同编号"
            @keyup.enter="handleQuery" />
        </el-form-item>

        <el-form-item label="申请时间" prop="createTime">
          <el-date-picker
            style="width: 100%"
            class="!w-360px"
            v-model="paramsData.createTime"
            type="datetimerange"
            range-separator="~" 
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            @change="scopeDateChange"
          />
        </el-form-item>

        <el-form-item label="申请部门" prop="deptId">
          <el-tree-select
            v-model="paramsData.deptId"
            class="!w-360px"
            :data="deptTree"
            filterable
            clearable
            :props="defaultProps"
            check-strictly
            default-expand-all
            placeholder="请选择申请部门"
            value-key="deptId"
          />
        </el-form-item>

        <el-form-item label="申请状态" prop="applyStatus">
          <el-select v-model="paramsData.applyStatus" class="!w-360px" clearable placeholder="请选择申请状态">
            <el-option v-for="item in statusList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button v-hasPermi="['wise:expense:query']" @click="handleQuery">
            <Icon class="mr-5px" icon="ep:search" />
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <Icon class="mr-5px" icon="ep:refresh" />
            重置
          </el-button>
          <el-button v-hasPermi="['wise:expense:create']" plain type="primary" @click="openForm(null)">
            <Icon class="mr-5px" icon="ep:plus" />
            新增
          </el-button>
          <el-button v-hasPermi="['wise:expense:export']" :loading="exportLoading" plain type="success"
            @click="handleExport"><Icon class="mr-5px" icon="ep:download" />导出</el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>
    <ContentWrap>
      <div class="applySum">申请金额（含税）汇总：￥{{ applySum ? applySum : '0.00' }}</div>
    </ContentWrap>
    <!-- 列表 -->
    <ContentWrap>
      <el-table v-loading="loading" :data="tableData" @selection-change="tableSelectionChange">
        <el-table-column type="selection" width="30" />
        <template v-for="item in tableColumn" :key="item.prop">
          <el-table-column
            show-overflow-tooltip
            :width="item.width"
            :align="item.align ? item.align : 'center'" 
            :label="item.label"
            :prop="item.prop"
          >
            <template #default="scope">
              <div v-if="item.prop === 'applyDepartment'">{{ scope.row.applyDepartment ? scope.row.applyDepartment : '-' }}</div>
              <div v-else-if="item.prop == 'requestAmountTax'">
                {{ scope.row.requestAmountTax || scope.row.requestAmountTax == 0 ? scope.row.requestAmountTax : '-' }}
              </div>
              <div v-else-if="item.prop == 'requestAmountNotTax'">
                {{ scope.row.requestAmountNotTax || scope.row.requestAmountNotTax == 0 ? scope.row.requestAmountNotTax : '-' }}
              </div>
              <div v-else-if="item.prop == 'createTime'">
                <p>{{ scope.row.createTime ? formatDate(scope.row.createTime) : '-' }}</p>
              </div>
              <div v-else-if="item.prop == 'applyStatus'">
                <el-tag type="warning" v-if="scope.row.applyStatus == 1">待提交</el-tag>
                <el-tag type="success" v-else-if="scope.row.applyStatus == 2">已提交</el-tag>
                <el-tag type="info" v-else-if="scope.row.applyStatus == 3">已作废</el-tag>
                <span v-else>-</span>
              </div>
              <div v-else-if="item.prop == 'creator'">
                  <p>
                    {{ 
                        scope.row.creator ? 
                        userList.find(item => item.id == scope.row.creator)?.username + 
                        `（${userList.find(item => item.id == scope.row.creator)?.mobile}）` || 
                        '-' : '-' 
                    }}
                  </p>
              </div>
              <div v-else>
                {{ scope.row[item.prop] || '-' }}
              </div>
            </template>
          </el-table-column>
        </template>

        <el-table-column :width="140" align="center" label="操作" fixed="right">
          <template #default="scope">
            <el-button v-if="scope.row.applyStatus !== 1" v-hasPermi="['wise:expense:update']" link type="primary" @click="openForm(scope.row.id)">
              查看
            </el-button>
            <el-button v-else v-hasPermi="['wise:expense:update']" link type="primary" @click="openForm(scope.row.id)">
              编辑
            </el-button>
            <el-button v-if="scope.row.applyStatus === 2" v-hasPermi="['wise:expense:delete']" link type="danger" @click="handleVoid(scope.row.id)">
              作废
            </el-button>
            <el-button v-else v-hasPermi="['wise:expense:delete']" link type="danger" @click="handleDelete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>

      </el-table>


      <!-- 分页 -->
      <Pagination v-model:limit="paramsData.pageSize" v-model:page="paramsData.pageNo" :total="total" @pagination="getList" />
    </ContentWrap>
  </div>
  <div v-else>
    <ExpenditureForm  ref="ExpenditureFormRef" />
  </div>
</template>
<script setup>
  import {ref,reactive, nextTick} from "vue"
  import { formatDateToYMDHMS } from '@/utils/index'
  import { defaultProps, handleTree } from '@/utils/tree'
  import * as DeptApi from '@/api/system/dept'
  import * as ExpenditureApi from '@/api/viewsApi/expenditure'
  import { formatDate } from '@/utils/formatTime'
  import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
  import ExpenditureForm from './expenditureForm.vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  const { wsCache } = useCache('sessionStorage')
  import download from '@/utils/download'
  const route = useRoute()
  const userList = wsCache.get(CACHE_KEY.USER_LIST) || []
  const pageStatus = ref(1) // 1列表页   2新增编辑页
  const statusList = [
    { name: '待提交', id: 1 },
    { name: '已提交', id: 2 },
    { name: '已作废', id: 3 },
  ]
  const paramsData = reactive({
    pageNo: 1,
    pageSize: 10,
    code: '',
    projectName: '',
    projectCode: '',
    mainContract: '', // 关联主合同名称
    mainContractCode: '', // 关联主合同编号
    deptId: '', // 申请部门
    createTime: [],
    applyStatus: undefined,
    ids: []
  })
  const message = useMessage() // 消息弹窗
  const { t } = useI18n() // 国际化
  const loading = ref(true) // 列表的加载中
  const total = ref(0) // 列表的总页数
  const tableData = ref([]) // 列表的数据
  const tableColumn = ref([
    { prop: 'code', label: '申请编号', align: 'center', width: 150},
    { prop: 'projectName', label: '项目名称', align: 'center'},
    { prop: 'projectCode', label: '项目编号', align: 'center'},
    { prop: 'mainContract', label: '主合同名称', align: 'center'},
    { prop: 'mainContractCode', label: '主合同编号', align: 'center'},
    { prop: 'requestAmountTax', label: '申请金额（含税）', align: 'center', width: 150},
    { prop: 'requestAmountNotTax', label: '申请金额（不含税）', align: 'center', width: 150},
    { prop: 'createTime', label: '申请时间', align: 'center', width: 160},
    { prop: 'creator', label: '申请人', align: 'center', width: 180},
    { prop: 'applyDepartment', label: '申请部门', align: 'center'},
    { prop: 'applyStatus', label: '申请状态', align: 'center'},
  ]) // 表格的列
  const queryFormRef = ref() // 搜索的表单
  const exportLoading = ref(false) // 导出的加载中
  const selectIds = ref([])
  const ExpenditureFormRef = ref()

  const applySum = ref(0)
  /** 查询角色列表 */
  const getList = async () => {
    loading.value = true
    try {
      const data = await ExpenditureApi.getExpenseList(paramsData)
      data.list.forEach((item, index) => {
        item.requestAmountTax = (item.requestAmountTax / 100).toFixed(2)
        item.requestAmountNotTax = (item.requestAmountNotTax / 100).toFixed(2)
      })

      tableData.value = data.list
      total.value = data.total
      setApplySum()
    } finally {
      loading.value = false
    }
  }
  provide('getList', getList)

  const scopeDateChange = (val) => {
    paramsData.createTime = [formatDateToYMDHMS(val[0]), formatDateToYMDHMS(val[1])]
  }


  /** 搜索按钮操作 */
  const handleQuery = () => {
    paramsData.pageNo = 1
    getList()
  }
  /** 重置按钮操作 */
  const resetQuery = () => {
    queryFormRef.value.resetFields()
    handleQuery()
  }
  const handleExport = async () => {
    if(selectIds.value.length > 0){
      paramsData.ids = selectIds.value
    }
    
    try {
      // 导出的二次确认
      await message.exportConfirm()
      // 发起导出
      exportLoading.value = true
      const data = await ExpenditureApi.exportExpense(paramsData)
      download.excel(data, '费用支付列表.xls')
    } catch {
    } finally {
      exportLoading.value = false
    }
  }
  const tableSelectionChange = (selection) => {
    selectIds.value = selection.map(item => item.id)
  }

  /** 作废按钮操作 */
  const handleVoid = async (id) => {
    let parms = {
      id,
      status: 3
    }
    try {
      // 删除的二次确认
      await ElMessageBox.confirm(
        `是否作废所选中数据？`
        ,'是否作废？',
          {
            confirmButtonText: t('common.ok'),
            cancelButtonText: t('common.cancel'),
            type: 'warning'
          }
        )
      await ExpenditureApi.voidExpense(parms)
      message.success(t('操作成功'))
      await getList()
    } catch {}
  }

  /** 删除按钮操作 */
  const handleDelete = async (id) => {
    try {
      // 删除的二次确认
      await message.delConfirm()
      // 发起删除
      await ExpenditureApi.deleteExpense(id)
      message.success(t('common.delSuccess'))
      // 刷新列表
      await getList()
    } catch {}
  }
  const openForm = (id) => {
    pageStatus.value = 2
    nextTick(() => {
      ExpenditureFormRef.value.init(id)
    })
  }
  function findDeptNameById(tree, id) {
    for (const node of tree) {
      if (node.id === id) {
        return node.name
      }
      if (node.children && node.children.length > 0) {
        const name = findDeptNameById(node.children, id)
        if (name) return name
      }
    }
    return ''
  }
  provide('findDeptNameById', findDeptNameById)
  function setApplySum() {
    let sum = tableData.value.reduce((pre, cur) => pre + Number(cur.requestAmountTax), 0)
    applySum.value = sum.toFixed(2)
  }
  const deptTree = ref() // 树形结构
  provide('deptTree', deptTree)
  /** 获得部门树 */
  const getTree = async () => {
    deptTree.value = []
    const data = await DeptApi.getSimpleDeptList()
    deptTree.value = handleTree(data)
  }
  /** 初始化 **/
  onMounted(async() => {
    await getTree()
    await getList()
    if(route.query.id){
      openForm(route.query.id)
    }
  })
  const goBack = () => {
    pageStatus.value = 1
    getList()
  }
  provide('goBack', goBack)

</script>
<style lang="scss" scoped>
.applySum {
    font-family: PingFang SC, PingFang SC;
    font-weight: 600;
    font-size: 14px;
    color: #1D1D1D;
}
</style>
